﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Yyd.Share;

namespace Yyd.Share
{
    /// <summary>
    /// 网关1.0 处理业务代码兼容
    /// </summary>
    public class StudentFilterAttribute : Attribute, IAsyncActionFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var input = context.ActionArguments.Values.Where(x => x is StudentBaseInput).FirstOrDefault();
            if (input != null)
            {
                StudentBaseInput baseOrderInput = input as StudentBaseInput;
                var ngexpand = context.HttpContext.GetHeaderValueAs<string>("ng-expand");
                //网关2.0 流量
                if (!string.IsNullOrEmpty(ngexpand))
                {
                    ngexpand = HttpUtility.UrlDecode(ngexpand);
                    var ngexpandRoot = JsonConvert.DeserializeObject<NgexpandRoot>(ngexpand);
                    baseOrderInput.UserId = ngexpandRoot.UcUser.UserId;
                    baseOrderInput.BrandId = ngexpandRoot.UcUser.BrandId;
                }
            }

            //提交的数据满足规则，继续往下走，触发Action执行
            var executedContext = await next().ConfigureAwait(false);

        }



    }


    public static class HeaderParser
    {
        public static T GetHeaderValueAs<T>(this HttpContext httpContext, string headerName)
        {
            HttpRequest httpRequest = httpContext.Request;
            StringValues values;

            if (httpRequest.HttpContext?.Request?.Headers?.TryGetValue(headerName, out values) ?? false)
            {
                string rawValues = values.ToString();   // writes out as Csv when there are multiple.

                if (!string.IsNullOrWhiteSpace(rawValues))
                    return (T)Convert.ChangeType(values.ToString(), typeof(T));
            }
            return default(T);
        }
    }
}
